//
//  WBBaseController.swift
//  simpleWeibo


import UIKit

class WBBaseController: UIViewController {
    var visitorInfoDic : [String : String]?
    let navigationBar: UINavigationBar = {
        let top = UIApplication.shared.statusBarFrame.size.height
        let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: top, width: UIScreen.cz_screenWidth(), height: 44))
        return navigationBar
    }()
    let navItem = UINavigationItem()
    var tableView : UITableView? = UITableView()
    var refresh : GDPRefreshControl?
    var isPullup = false
    
    override var title: String? {
        didSet {
            navItem.title = title
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        WBNetWorkManager.shared.userLogon ? loadData() : ()
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(WBUserLoginSuccessNotification), object: nil)
    }
    
    //加载数据 具体的实现让子类负责
    @objc func loadData() {
        refresh?.endRefreshing()
    }
    
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 访客视图监听方法
extension WBBaseController {
    
    @objc fileprivate func loginSuccess (n: Notification) {
        print("登录成功")
        //更新UI 将访客视图 替换为表格视图
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        //需要重置view
        //在访问view的getter方法时 如果view = nil  会调用 loadView -> viewDidLoad
        view = nil
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func didClickLoginButton() {
        print("login")
        NotificationCenter.default.post(name: NSNotification.Name(WBUserShouldLoginNotification), object: nil)
    }
    
    @objc fileprivate func didClickRegisterButton() {
        print("register")
    }
}

// MARK: - SetUp
extension WBBaseController {
    
    fileprivate func setupUI() {
        
        view.backgroundColor = UIColor.white
//        automaticallyAdjustsScrollViewInsets = false
        setupNav()
        (WBNetWorkManager.shared.userLogon) ? setupTableView() : setupVisitorView()
    }
    
    //用户登录之后执行
    //子类重写此方法 因为子类不需要关心 用户登录之前的逻辑
    func setupNav() {
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
        //设置导航条 整体的渲染颜色
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        //设置导航条 的标题 字体颜色
        navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.darkGray]
        //设置系统按钮 的字体颜色
        navigationBar.tintColor = UIColor.orange
    }
    
    @objc func setupTableView() {
        let top = UIApplication.shared.statusBarFrame.size.height
        let tableViewTop = navigationBar.bounds.height + top
        let tabBarHeight = CGFloat(((tabBarController?.tabBar.bounds.height) != nil) ? 49 : 0)
        let tableViewHeight = UIScreen.cz_screenHeight() - tableViewTop - tabBarHeight
        let tableViewFrame = CGRect.init(x: 0, y: tableViewTop, width: UIScreen.cz_screenWidth(), height: tableViewHeight)
        tableView = UITableView.init(frame: tableViewFrame, style: .plain)
        tableView?.tableFooterView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        tableView?.scrollIndicatorInsets = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: 0, right: 0)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        tableView?.dataSource = self
        tableView?.delegate = self
        
        //设置刷新控件
        refresh = GDPRefreshControl()
        tableView?.addSubview(refresh!)
        refresh?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    
    func setupVisitorView() {
        let vistorView = WBVistorView(frame: view.bounds)
        view.insertSubview(vistorView, belowSubview: navigationBar)
        
        vistorView.visitorInfo = visitorInfoDic
        
        vistorView.loginButton.addTarget(self, action: #selector(didClickLoginButton), for: .touchUpInside)
        vistorView.registerButton.addTarget(self, action: #selector(didClickRegisterButton), for: .touchUpInside)
        
        //设置访客视图时 导航条左右按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(didClickRegisterButton))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(didClickLoginButton))
    }
}

// MARK: - UITableViewDataSource && UITableViewDelegate
extension WBBaseController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //最后组
        let section = tableView.numberOfSections - 1
        //最后一行
        let row = tableView.numberOfRows(inSection: section) - 1
        if section < 0 || row < 0 {
            return
        }
        if indexPath.section == section && indexPath.row == row && !isPullup {
            print("上拉刷新")
            isPullup = true
            loadData()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }

}

